package chapter03;

public class SingleList<E> {

    private int size;
    private Node head;

    public SingleList() {
        init();
    }

    private void init() {
        this.size = 0;
        head = new Node();
    }

    /**
     * 返回链表大小的方法
     * @return
     */
    public int size() {
        return size;
    }

    public void print() {
        Node p = head.next;
        while (p != null) {
            p = p.next;
            System.out.print("->" + p);
        }
        System.out.println();
    }

    public boolean contains(E e) {
        Node p = head.next;
        while (p != null && !p.data.equals(e)) {
            p = p.next;
        }
        return p != null;
/*
        while (p != null) {
            if (e.equals(p.data)) {
                return true;
            }else {
                p = p.next;
            }
        }
        return false;
*/
    }

    public boolean add(E e) {
        if (contains(e)) {
            return false;
        }
        Node tailer = head;  //尾随者
        Node p = head.next;
        while (p != null) {
            tailer = p;
            p = p.next;
        }
        tailer.next = new Node(e);//等价于 tailer.next = new Node(e, p);
        size++;
        return true;
    }

    public boolean remove(E e) {
        if (!contains(e)) {
            return false;
        }
        Node tailer = head;
        Node p = head.next;
        while (!p.data.equals(e)) {
            tailer = p;
            p = p.next;
        }
        tailer.next = p.next;
        size--;
        return true;
    }


    private class Node<E> {
        private E data;
        private Node next;

        public Node() {
            this(null);
        }

        public Node(E data) {
            this(data, null);
        }

        public Node(E data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

}
